package com.gyhy.dumplings.ware.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gyhy.dumplings.common.dto.WareDto;
import com.gyhy.dumplings.common.exception.BizCodeEnum;
import com.gyhy.dumplings.common.utils.R;
import com.gyhy.dumplings.ware.entity.WareEntity;
import com.gyhy.dumplings.ware.feign.ProductFeignService;
import com.gyhy.dumplings.ware.service.WareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @author 光影灰翼
 */
@RestController
@RequestMapping("/ware")
public class WareController {
    @Autowired
    private WareService wareService;

    @Autowired(required = false)
    private ProductFeignService productFeignService;

    @PostMapping("/updateWare")
    public R updateWare(@RequestBody List<WareDto> wareDtoList) throws Exception {
        // 1、feign调用product服务获得wareId
        System.out.println(JSON.toJSONString(wareDtoList));
        R newWareDtoListR = productFeignService.getWareInfo(wareDtoList);
        if (newWareDtoListR.getCode() == 0) {
            // 2、如果获取成功则开始对仓库进行更新
            // 2.1、获取仓库需要减去的存储量
            List<WareDto> newWareDtoList = newWareDtoListR.getData(new TypeReference<List<WareDto>>(){});
            System.out.println(newWareDtoList);
            HashMap<Integer, Integer> map = new HashMap<>();
            for (WareDto wareDto : newWareDtoList) {
                map.put(wareDto.getWareId(), map.getOrDefault(wareDto.getWareId(), 0) + wareDto.getCost() * wareDto.getProductNum());
            }

            // 2.2、获取仓库数量，防止仓库的库存小于0
            List<Integer> ids = new ArrayList<>(map.keySet());
            List<WareEntity> wareEntityList = wareService.listByIds(ids);

            // 2.3、检测仓库的库存是否小于0
            for (WareEntity wareEntity : wareEntityList) {
                Integer newCount=wareEntity.getStock()-map.get(wareEntity.getWareId());
                if(newCount<0){
                    return R.error(BizCodeEnum.NO_STOCK_EXCEPTION.getCode(),BizCodeEnum.NO_STOCK_EXCEPTION.getMessage());
                }
                wareEntity.setStock(newCount);
            }
            // 2.3、更新仓库
            Boolean isSuccess=wareService.updateBatchById(wareEntityList);
            return R.ok().setData(isSuccess);

        }else {
            return R.error(BizCodeEnum.STOCK_UPDATE_EXCEPTION.getCode(),BizCodeEnum.STOCK_UPDATE_EXCEPTION.getMessage());
        }
    }

}